﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oplaco.Web.DTO;


public partial class Controls_Admin_ManageCategoryControl : System.Web.UI.UserControl
{
    private string noItemSelected = "No item has been selected";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) {

            lstCategories.DataSource = this.loadCategoryList(0);
            lstCategories.DataBind();
            lstCategories.SelectedIndex = 0; 

        }
    }

    protected void AddCategoryButton_Click(object sender, EventArgs e) {
        try
        {
            int selectedCategoryId = 0;
            if (!String.IsNullOrEmpty(lstCategories.SelectedValue)) selectedCategoryId = Int32.Parse(lstCategories.SelectedValue);
            if (!String.IsNullOrEmpty(txtCategory.Text))
            {

                if (selectedCategoryId <= 0) selectedCategoryId = 0;
                CategoryManager.Add(selectedCategoryId, txtCategory.Text);
                lblMessage.Text = String.Format("The item with title {0} has been added", new string[] { txtCategory.Text });
                lblMessage.CssClass = "success";
                lblMessage.Visible = true;                
            }
            else
            {
                lblAddCategory.CssClass = "error";
                lblMessage.Text = noItemSelected;
                lblMessage.CssClass = "error";
                lblMessage.Visible = true;
            }

            this.reset();
        }
        catch (Exception exception) {
            lblMessage.Text = exception.Message.ToString();
            lblMessage.Visible = true;
            lblMessage.CssClass = "error";
        }
    }

    protected void DeleteCategoryButton_Click(object sender, EventArgs e) {
        lblMessage.Visible = true;
        try
        {
            int selectedCategoryId = 0;

            if (lstCategories.SelectedIndex <= 0 && lstChildCategories.SelectedIndex<=0)
            {
                lblMessage.Text = noItemSelected;
                lblMessage.CssClass = "error";
            }
            else {

                if (lstCategories.SelectedIndex>0)
                {
                    selectedCategoryId = Int32.Parse(lstCategories.SelectedValue);
                    lblMessage.Text = String.Format("The selected item with title {0} and id {1} has been removed", new string[] { lstCategories.SelectedItem.Text, lstCategories.SelectedValue });
                }

                if (lstChildCategories.SelectedIndex>0)
                {
                    selectedCategoryId = Int32.Parse(lstChildCategories.SelectedValue);
                    lblMessage.Text = String.Format("The selected item with title {0} and id {1} has been removed", new string[] { lstChildCategories.SelectedItem.Text, lstChildCategories.SelectedValue });
                }

                CategoryManager.Remove(selectedCategoryId);
                
                lblMessage.CssClass = "success";

            }

            lblMessage.Visible = true;
            this.reset();
        }
        catch (Exception exception) {
            lblMessage.Text = exception.Message.ToString();
            lblMessage.CssClass = "error";            
        }
    }

    /// <summary>
    /// Updates the selected category title
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void RenameCategoryButton_Click(object sender, EventArgs e) {

        try
        {
            int selectedCategoryId = 0;
            if (lstCategories.SelectedIndex <= 0 && lstChildCategories.SelectedIndex<=0)
            {
                lblMessage.Text = noItemSelected;
                lblMessage.CssClass = "error";
            }
            else 
            {

                if (lstCategories.SelectedIndex>0)
                {
                    selectedCategoryId = Int32.Parse(lstCategories.SelectedValue);
                    lblMessage.Text = String.Format("The selected item with title {0} and id {1} have been updated", new string[] { lstCategories.SelectedItem.Text, lstCategories.SelectedValue });
                }

                if (lstChildCategories.SelectedIndex>0)
                {
                    selectedCategoryId = Int32.Parse(lstChildCategories.SelectedValue);
                    lblMessage.Text = String.Format("The selected item with title {0} and id {1} have been updated", new string[] { lstChildCategories.SelectedItem.Text, lstChildCategories.SelectedValue });
                }

                CategoryManager.Update(selectedCategoryId, txtRenameCategory.Text);                
                lblMessage.CssClass = "success";
                
            }
            

            lblMessage.Visible = true;
            this.reset();
        }
        catch (Exception exception) {
            lblMessage.Text = exception.Message.ToString();
            lblMessage.CssClass = "error";    
        
        }
    
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lstCategories_IndexChanged(object sender, EventArgs e) {
        if (lstCategories.SelectedIndex > 0)
        {
            btnDelete.Enabled = true;
            btnAddCategory.Enabled = true;
            btnRenameCategory.Enabled = true;
            txtRenameCategory.Enabled = true;
            txtRenameCategory.Text = lstCategories.SelectedItem.Text;

            List<ListItem> coll = this.loadCategoryList(int.Parse(lstCategories.SelectedValue));
            if (coll != null) {                             

                lstChildCategories.DataSource = coll;
                lstChildCategories.DataBind();
                lstChildCategories.SelectedIndex = 0;

                if(coll.Count() > 1) btnDelete.Enabled = false; //user should not delete main category when it still has child categories
            }

            lblMessage.Text = "Your current selection: " + lstCategories.SelectedItem.Text;
            lblMessage.CssClass = "success";
            lblMessage.Visible = true;
        }
        else {
            lblMessage.Text = "Manage categories";
            this.reset();
        }
    }


    protected void lstChildCategories_IndexChanged(object sender, EventArgs e) {
        lblMessage.Text = "Your current selection: " + lstCategories.SelectedItem.Text;
        if (lstChildCategories.SelectedIndex > 0) { 
            
            lblMessage.Text += " ; " + lstChildCategories.SelectedItem.Text;
            btnDelete.Enabled = true;
            btnAddCategory.Enabled = false;
            btnRenameCategory.Enabled = true;
            txtRenameCategory.Enabled = true;
            txtRenameCategory.Text = lstChildCategories.SelectedItem.Text;
        }
    }

    /// <summary>
    /// Hmmmm, should have made the collection not a List, better to use ListItemCollection
    /// </summary>
    private List<ListItem> loadCategoryList(int parentId) {
        lstCategories.DataTextField = "Text";
        lstCategories.DataValueField = "Value";

        lstChildCategories.DataTextField = "Text";
        lstChildCategories.DataValueField = "Value";

        List<ListItem> list = null;
        //work dynamic,..
        CategoryManager.ClearCache(HttpContext.Current);

        CachedCategoryCollection categories = CategoryManager.Fetch(HttpContext.Current, 100);
        if (categories != null && categories.Count() > 0)
        {

            if (parentId == 0) list = (from item in categories select new ListItem(item.Title, item.Id.ToString())).ToList<ListItem>();
            else list = (from item in categories where item.HasChilds==true
                         select item.ChildCollection into x
                         from child in x
                         where child.ParentId == parentId
                         select new ListItem(child.Title, child.Id.ToString())).ToList<ListItem>();

            list.Insert(0, new ListItem("--- Select ---", "-1"));

            
        }

        return list;
    }

    private void reset() {
        
        lstCategories.DataSource = this.loadCategoryList(0);
        lstCategories.DataBind();
        lstCategories.SelectedIndex = 0; 

        List<ListItem> list = new List<ListItem>();
        ListItem item = new ListItem("--- Select ---", "-1");
        list.Insert(0, item);
        lstChildCategories.SelectedIndex = -1;
        lstChildCategories.DataSource = list;
        lstChildCategories.DataBind();


        txtCategory.Text = String.Empty;
        txtRenameCategory.Text = String.Empty;
    
    }
}